<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Action\Workbench\Tag;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Logic\AppTrait;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactTagContract;
use MoChat\App\WorkContact\Contract\WorkContactTagPivotContract;
use MoChat\App\WorkContact\QueueService\Tag\DeleteApply;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Plugin\ContactTrack\Constants\Event;
use MoChat\Plugin\ContactTrack\Constants\EventName;
use MoChat\Plugin\ContactTrack\Contract\ContactTrackContract;

/**
 * 设置客户企业标签.
 *
 * Class CreateContactTag
 * @Controller
 */
class DeleteContactTag extends AbstractAction
{
    use AppTrait;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeContract;

    /**
     * @Inject
     * @var WorkContactTagContract
     */
    protected $workContactTagContract;

    /**
     * @var DeleteApply
     */
    protected $service;

    /**
     * @Inject
     * @var WorkContactContract
     */
    private $workContactContract;

    /**
     * 客户 - 标签关联.
     * @Inject
     * @var WorkContactTagPivotContract
     */
    private $contactTagPivotContract;

    /**
     * 互动轨迹表.
     * @Inject
     * @var ContactTrackContract
     */
    private $track;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * 参数.
     * @var array
     */
    private $params;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/workContact/deleteContactTag", methods="DELETE")
     */
    public function handle(): array
    {
        $params['tagId'] = (int) $this->request->input('tagId');
        $params['contactId'] = (int) $this->request->input('contactId', 0);
        # # 客户标签
        $list = $this->contactTagPivotContract->getWorkContactTagPivotsByContactIdsTagIds([$params['contactId']], [$params['tagId']], ['id', 'contact_id', 'employee_id', 'contact_tag_id']);
        if (empty($list)) {
            return [];
        }
        # # 删除本地客户标签
        $this->contactTagPivotContract->deleteWorkContactTagPivots(array_column($list, 'id'));
        # # 同步到企业微信
        $tagInfo = $this->workContactTagContract->getWorkContactTagById($params['tagId'], ['name', 'wx_contact_tag_id', 'contact_tag_group_id']);
        if (empty($tagInfo)) {
            return [];
        }
        # # 员工
        $employee = $this->workEmployeeContract->getWorkEmployeeById(user()['id'], ['name', 'wx_user_id']);
        foreach ($list as $item) {
            # # 员工
            $employeeInfo = $this->workEmployeeContract->getWorkEmployeeById($item['employeeId'], ['name', 'wx_user_id']);
            if (empty($employeeInfo)) {
                continue;
            }
            $tagData['userid'] = $employeeInfo['wxUserId'];
            # # 客户
            $contact = $this->workContactContract->getWorkContactById($params['contactId'], ['wx_external_userid']);
            $tagData['external_userid'] = $contact['wxExternalUserid'];
            $tagData['remove_tag'] = [$tagInfo['wxContactTagId']];
            $wx = $this->wxApp(user()['corpId'], 'contact')->external_contact;
            $res = $wx->markTags($tagData);
            if ($res['errcode'] !== 0) {
                $this->logger->error(sprintf('%s [%s] %s', '客户取消标签失败', date('Y-m-d H:i:s'), Json::encode($res, JSON_THROW_ON_ERROR)));
                throw new CommonException($res['errcode'], $res['errmsg']);
            }
        }

        # # 记录轨迹
        $content = '员工' . $employee['name'] . '取消了Ta的标签 「' . $tagInfo['name'] . '」';
        $this->recordTrack($content, user()['id'], $params['contactId']);
        return [];
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'tagId' => 'required',
            'contactId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'tagId.required' => '标签id 必传',
            'contactId.required' => '客户id必传',
        ];
    }

    /**
     * 记录轨迹.
     */
    private function recordTrack(string $content, int $employeeId, int $contactId)
    {
        $jsonContact = [
            'title' => EventName::TAG_DELETE,
            'content' => $content,
        ];
        $data = [
            'employee_id' => $employeeId,
            'contact_id' => $contactId,
            'content' => Json::encode($jsonContact),
            'corp_id' => user()['corpId'],
            'event' => Event::TAG_DELETE,
        ];

        $res = $this->track->createContactTrack($data);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '记录轨迹失败');
        }
    }
}
